<template>
  <q-input
    :style="{ width: width + 'px', height: '40px' }"
    :label="label"
    @clear="onClear"
    autocomplete="off"
    clearable
    dense
    filled
    ref="input"
    v-model="triggerModel"
    dark
    color="grey-5"
  >
    <q-popup-proxy @keyup.enter="onConfirm" v-model="open" dark>
      <div class="q-pa-md q-gutter-md">
        <q-input autocomplete="off" dark filled v-model="date">
          <template v-slot:prepend>
            <q-icon name="event" class="cursor-pointer">
              <q-popup-proxy transition-show="scale" transition-hide="scale">
                <q-date :locale="locale" v-model="date" mask="YYYY-MM-DD HH:mm">
                  <div class="row items-center justify-end">
                    <q-btn v-close-popup label="关闭" color="primary" flat />
                  </div>
                </q-date>
              </q-popup-proxy>
            </q-icon>
          </template>

          <template v-slot:append>
            <q-icon name="access_time" class="cursor-pointer">
              <q-popup-proxy transition-show="scale" transition-hide="scale">
                <q-time :locale="locale" v-model="date" mask="YYYY-MM-DD HH:mm" format24h>
                  <div class="row items-center justify-end">
                    <q-btn v-close-popup label="关闭" color="primary" flat />
                  </div>
                </q-time>
              </q-popup-proxy>
            </q-icon>
          </template>
        </q-input>

        <div>
          <q-btn class="full-width" color="primary" label="确认" @click="onConfirm" />
        </div>
      </div>
    </q-popup-proxy>
  </q-input>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue';

import { dayjs } from 'src/utils/dayjs';
import { locale } from 'src/components/search/utils';

export default defineComponent({
  name: 'search-date',

  props: {
    label: {
      type: String,
      required: true,
    },
    field: {
      type: String,
      required: true,
    },
    width: {
      type: Number,
      default: 200,
    },
    initRecent: {
      type: Number,
    },
    initDateType: {
      type: String,
    },
  },

  setup(props, { emit }) {
    const open = ref(false);
    const triggerModel = ref('');
    const format = 'YYYY-MM-DD HH:mm:ss';

    const date = ref(dayjs().format(format));

    const onConfirm = () => {
      const date1 = dayjs(date.value).format(format);
      emit('updateTime', { field: props.field, clause: date1 });
      open.value = false;
      triggerModel.value = date1;
    };

    const onClear = () => {
      triggerModel.value = '';
      emit('updateTime', { field: props.field, clause: '' });
    };

    return {
      open,
      locale,
      date,
      triggerModel,
      onClear,
      onConfirm,
    };
  },
});
</script>
